import modelEnhance from '@/utils/modelEnhance';
import PageHelper from '@/utils/pageHelper';
import { noticeGlobal} from "@/utils/core";

/**
 * 当第一次加载完页面时为true
 * 可以用这个值阻止切换页面时
 * 多次初始化数据
 */
let LOADED = false;
export default modelEnhance({
  namespace: 'studentstate',

  state: {
    pageData: PageHelper.create(),
    userList: [],
    roleList: PageHelper.create(),
    userRoleIds: [],
    t_userRoleIds: [],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/studentstate' && !LOADED) {
          LOADED = true;
          dispatch({
            type: 'init'
          });
        }
      });
    }
  },

  effects: {
    // 进入页面加载
    *init({ payload }, { call, put, select }) {
      const { pageData } = yield select(state => state.studentstate);
      yield put({
        type: 'getPageInfo',
        payload: {
          pageData: pageData.startPage(1, 10)
        }
      });
      // yield put.resolve({
      //   type: '@request',
      //   payload: {
      //     // valueField: 'roleList',
      //     actionType: 'setRoleList',
      //     url: '/api/authManage/role/listAll',
      //     data: {},
      //     afterResponse: resp=> resp.data,
      //   }
      // })
    },
    // 获取分页数据
    *getPageInfo({ payload }, { call, put }) {
      const { pageData } = payload;
      yield put.resolve({
        type:'@request',
        payload: {
          actionType: 'setUserList',
          url: '/api/statistics/lessonUserReport',
          data: pageData.pageinfoData(),
        }
      })
    },
    // 导出分页数据
    *exportPageInfo({ payload }, { call, put }) {
      const { pageData } = payload;
      console.log(pageData)
      yield put.resolve({
        type:'@request',
        payload: {
          actionType: 'exportPageInfo',
          url: '/api/statistics/excel/lessonUserReport',
          data: pageData,
          responseType: 'blob',
          afterResponse: resp=> {
            const blob = new Blob([resp], {type: 'application/vnd.ms-excel'});
            const fileName = '学员学习统计.xls'; // 自定义文件名
            const link = document.createElement('a'); // 动态创建a标签
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.click(); // 触发点击事件下载
            window.URL.revokeObjectURL(link.href);
          },
        }
      })
    },
    // 保存 之后查询分页
    *save({ payload }, { call, put, select, take }) {
      const { values, success } = payload;
      const { pageData } = yield select(state => state.studentstate);
      // put是非阻塞的 put.resolve是阻塞型的
      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          url: '/api/authManage/user/addNewUsers',
          data: {userList: [values]}
        }
      });

      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
      success();
    },
    // 修改
    *update({ payload }, { call, put, select }) {
      const { values, success } = payload;

      const { pageData } = yield select(state => state.studentstate);
      yield put.resolve({
        type: '@request',
        payload: {
          notice: true,
          url: '/api/authManage/user/update',
          data: values,
        }
      });

      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
      success();
    },
    // 删除 之后查询分页
    *remove({ payload }, { call, put, select }) {
      const { records, success } = payload;
      const { pageData } = yield select(state => state.studentstate);
      yield put({
        type: '@request',
        payload: {
          notice: true,
          method: 'DELETE',
          url: '/api/authManage/user/delete/userIds',
          data: {idList: records.map(item => item.id)}
        }
      });
      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
      success();
    },
    *updateIsActive({payload}, {call, put, select}){
      const {val, record } = payload;
      const { pageData } = yield select(state => state.users);

      yield put.resolve({
        type: '@request',
        payload:{
          notice: true,
          url: '/api/authManage/user/updateActiveStatus',
          data: {activeStatus: val, userIds: [record.id] }
        }
      });

      yield put({
        type: 'getPageInfo',
        payload: { pageData }
      });
    },
    *getRoleList({payload}, {call, put, select}){
      yield put.resolve({
        type: '@request',
        payload: {
          // valueField: 'roleList',
          actionType: 'setRoleList',
          url: '/api/authManage/role/listAll',
          data: {},
          afterResponse: resp=> resp.data,
        }
      })
    },
    *getUserRoleList({payload}, {call, put}){
      const { userId } = payload;
      yield put.resolve({
        type: '@request',
        payload:{
          actionType:'setUserRoleList',
          url: '/api/authManage/role/byUserId/' + userId,
          method:'GET',
          afterResponse:resp => resp.data.map(item => item.id),
        }
      })
    },
    *updateUserRole({payload}, {call, put, select}){
      const { roleIds, record, success } = payload;
      const { userRoleIds } = yield select(state => state.users);
      const minus_userRoleKeys = userRoleIds.filter(v=> {return roleIds.indexOf(v) == -1});
      if(roleIds.length > 0){
        yield put.resolve({
          type: '@request',
          payload:{
            url: '/api/authManage/user/assignRoles',
            data: roleIds.map(item=> {return {roleId: item, userId: record.id }})
          }
        });
      }
      if(minus_userRoleKeys.length> 0){
        yield put.resolve({
          type: '@request',
          payload:{
            url: '/api/authManage/role/unassignPermissions',
            data: minus_userRoleKeys.map(item=> {return {roleId: item, userId: record.id }})
          }
        });
      }

      success();
    },
  },

  reducers: {
    setUserList_SUCCESS(state, {payload}){
      let { pageData } = state;
      return {
        ...state,
        pageData: pageData.setPage(payload)
      };
    },
    setRoleList_SUCCESS(state, {payload}){
      let {roleList} = state;
      const {records, current, page, total, size} =  payload;
      return {
        ...state,
        roleList: {...roleList, list: records, pageNum: current, pageSize: page, totalPages: total }
      };
    },
    setUserRoleList_SUCCESS(state, {payload}){
      return {
        ...state,
        userRoleIds: payload,
        t_userRoleIds: payload,
      }
    }
  }
});
